package com.tanhua.api.mongo;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.mongo.FollowUser;
import com.tanhua.mongo.Video;
import com.tanhua.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VideoApiImpl implements VideoApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdService idService;

    @Override
    public PageBeanVo findByPage(Integer pageNum, Integer pageSize) {
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC, "created"));
        query.skip((pageNum - 1) * pageSize).limit(pageSize);
        List<Video> videos = mongoTemplate.find(query, Video.class);
        System.out.println(videos);
        long count = mongoTemplate.count(query, Video.class);
        System.out.println(count);
        PageBeanVo pageBeanVo = new PageBeanVo(pageNum, pageSize, count, videos);
        return pageBeanVo;
    }

    @Override
    public void save(Video video) {
        // 指定小视频发布时间和vid
        video.setCreated(System.currentTimeMillis());
        video.setVid(idService.getNextId("video"));
        // 保存
        mongoTemplate.save(video);
    }

    @Override
    public void saveFollowUser(FollowUser followUser) {
        mongoTemplate.insert(followUser);
    }

    @Override
    public void removeFollowUser(Long userId, Long followUserId) {
        Query query = new Query(Criteria.where("followUserId").is(followUserId).and("userId").is(userId));
        mongoTemplate.remove(query, FollowUser.class);
    }

    @Override
    public PageBeanVo findUserVideo(Integer page, Integer pagesize, Long uid) {
        Query query = new Query(Criteria.where("userId").is(uid));
        query.with(new Sort(Sort.Direction.DESC, "created"));
        query.skip((page - 1) * pagesize).limit(pagesize);
        List<Video> videos = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);
        PageBeanVo pageBeanVo = new PageBeanVo(page, pagesize, count, videos);
        return pageBeanVo;
    }

    @Override
    public Video findById(String videoId) {
        return mongoTemplate.findById(new ObjectId(videoId),Video.class);
    }
}
